package sardine.monitor;

import io.netty.handler.codec.http.HttpResponseStatus;
import sardine.log.Logs;

import java.time.LocalDateTime;
import java.util.concurrent.atomic.AtomicLong;

/**
 * 监控是微服务必不可少的特性
 *
 * @auth bruce-sha
 * @date 2015/5/22
 */
public class Metrics {

    static final LocalDateTime startTime = LocalDateTime.now();//开始时间

    static final AtomicLong totalRequestCount = new AtomicLong();//总请求数
    static final AtomicLong totalResponseTime = new AtomicLong();//总请求时间
    static final AtomicLong totalResponseBytes = new AtomicLong();
    static final AtomicLong staticRequestCount = new AtomicLong();//静态文件请求数

    static final AtomicLong response1xxCount = new AtomicLong();
    static final AtomicLong response2xxCount = new AtomicLong();
    static final AtomicLong response3xxCount = new AtomicLong();
    static final AtomicLong response4xxCount = new AtomicLong();
    static final AtomicLong response5xxCount = new AtomicLong();


    public static String alive() {
        return LocalDateTime.now().toString();
    }

    public static long totalRequestCount() {
        long c = totalRequestCount.incrementAndGet();
        Logs.debug(() -> "sardine total request count: " + c);
        return c;
    }

    public static long totalResponseTime(long time) {
        long t = totalResponseTime.addAndGet(time);
        Logs.debug(() -> "sardine total request time: " + t);
        return t;
    }

    public static long staticRequestCount() {
        return staticRequestCount.incrementAndGet();
    }

    public static void responseStatusCount(HttpResponseStatus status) {

        final int statusCode = status.code();

        switch (statusCode / 100) {
            case 1:
                long c = response1xxCount.incrementAndGet();
                Logs.debug(() -> "sardine 1xx status code count: " + c);
                break;
            case 2:
                c = response2xxCount.incrementAndGet();
                Logs.debug(() -> "sardine 2xx status code count: " + c);
                break;
            case 3:
                c = response3xxCount.incrementAndGet();
                Logs.debug(() -> "sardine 3xx status code count: " + c);
                break;
            case 4:
                c = response4xxCount.incrementAndGet();
                Logs.debug(() -> "sardine 4xx status code count: " + c);
                break;
            case 5:
                c = response5xxCount.incrementAndGet();
                Logs.debug(() -> "sardine 5xx status code count: " + c);
                break;
            default:
                Logs.debug(() -> "sardine unknown status code: " + statusCode);
                break;
        }
    }

//    @FunctionalInterface
//    public interface Recordable {
//
//        Object record();
//
//        default String asString() {
//            return Objects.toString(record(), "");
//        }
//
//    }
}
